package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings;
import com.yuntongxun.ecdemo.common.utils.ECPreferences;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.core.ClientUser;
import com.yuntongxun.ecdemo.core.ContactsCache;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.LauncherActivity;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecdemo.ui.contact.ContactLogic;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.PostResult;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.comman.EventBusTags;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.util.CommonUtils;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECInitParams;
import com.yuntongxun.ecsdk.SdkErrorCode;

import java.io.InvalidClassException;
import java.util.ArrayList;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * VoiceChat登录
 * <p>
 * 修改登陆界面
 *
 * @author li_zhuonan
 * @since 2016/11/18
 */
public class VoiceChatLoginActivity extends BaseVoiceChatActivity implements ICommonViewUi {

    @InjectView(R.id.user_name_et)
    EditText userNameEt;
    @InjectView(R.id.user_password_et)
    EditText userPasswordEt;

    @InjectView(R.id.login_remember_cb)
    CheckBox rememberCb;

    private ICommonRequestPresenter iCommonRequestPresenter;

    private ECProgressDialog mPostingdialog;


    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    public void onEvent(PostResult postResult){
        if (EventBusTags.REGISTER_FINISH.equals(postResult.getTag())){
            finish();
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_voice_chat_login;
    }

    @Override
    protected void initViewsAndEvents() {

        setTitle(getString(R.string.login_title));
        setRightTitle(getString(R.string.register_title));
        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);
        if (!PreferenceUtils.getPrefString(this, Contants.Preference.USER_NAME,"").equals("")){
            userNameEt.setText(PreferenceUtils.getPrefString(this, Contants.Preference.USER_NAME,""));
            userPasswordEt.setText(PreferenceUtils.getPrefString(this, Contants.Preference.USER_PSD,""));
        }
        registerReceiver(new String[] { SDKCoreHelper.ACTION_SDK_CONNECT });



    }

    @Override
    public void clickRightTv() {
        super.clickRightTv();


    }

    @OnClick({R.id.forget_password_tv, R.id.login_btn, R.id.register_tv,R.id.toolbar_right_title})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forget_password_tv:
                startActivity(new Intent(VoiceChatLoginActivity.this, ForgetPsdActivity.class));
                break;
            case R.id.login_btn:

//                Intent intent = new Intent(mContext, LauncherActivity.class);
//                startActivity(intent);
                mPostingdialog = new ECProgressDialog(this, R.string.login_posting);
                mPostingdialog.show();
                toRequest(ApiConstants.EventTags.ACCOUNT_LOGIN);

                break;
            case R.id.register_tv:
//                startActivity(new Intent(VoiceChatLoginActivity.this, VoiceChatRegisterActivity.class));
                break;
            case R.id.toolbar_right_title:
                startActivity(new Intent(VoiceChatLoginActivity.this, RegisterFlagActivity.class));
                break;
        }
    }



    @Override
    public void toRequest(int eventTag) {

        if(eventTag == ApiConstants.EventTags.ACCOUNT_LOGIN){
            //账号登录

            String accountName = userNameEt.getText().toString();
            String accountPwd = userPasswordEt.getText().toString();

            if(CommonUtils.isEmpty(accountName)){
                showToastShort(getString(R.string.account_name_empty));
                mPostingdialog.dismiss();
                return;
            }

            if(CommonUtils.isEmpty(accountPwd)){
                showToastShort(getString(R.string.password_empty));
                mPostingdialog.dismiss();
                return;
            }

            RequestParams params = new RequestParams();
            params.put("accountName", accountName);
            params.put("accountPwd", accountPwd);

            iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.ACCOUNT_LOGIN, params);
        }
    }

    String email="";
    UserInfo info;
    @Override
    public void getRequestData(int eventTag, String result) {
        JsonHelper<UserInfo> jsonHelper = new JsonHelper<UserInfo>(UserInfo.class);
        info = jsonHelper.getData(result, "result");

        PreferenceUtils.setPrefString(this, Contants.Preference.user_info,result);
        if (rememberCb.isChecked()){
            PreferenceUtils.setPrefString(this, Contants.Preference.USER_NAME,userNameEt.getText().toString().trim());
            PreferenceUtils.setPrefString(this, Contants.Preference.USER_PSD,userPasswordEt.getText().toString().trim());
        }else{
            PreferenceUtils.setPrefString(this, Contants.Preference.USER_NAME,"");
            PreferenceUtils.setPrefString(this, Contants.Preference.USER_PSD,"");
        }

        String appKey = Contants.VOICE_APP_KEY;
        String token = Contants.VOICE_APP_TOKEN;
        email=userNameEt.getText().toString().trim();
        ClientUser clientUser = new ClientUser(info.getId());
        clientUser.setAppKey(appKey);
        clientUser.setAppToken(token);
        clientUser.setLoginAuthType(ECInitParams.LoginAuthType.NORMAL_AUTH);
        clientUser.setPassword("");
        CCPAppManager.setClientUser(clientUser);

        ECContacts contact = new ECContacts();
//        String message = info.getNickName() + "-" + info.getGender() + "-" + info.getAge() + "-" + info.getCountry() + "-" + info.getNativeLanguage() + "-" + info.getLearningLanguage();
        StringBuffer message= new StringBuffer();
        message.append("{\"result\":" );
        message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
        message.append("\"nickName\":\"" + info.getNickName() + "\",");
        message.append("\"id\":\"" + info.getId() + "\",");
        message.append("\"gender\":\"" + info.getGender() + "\",");
        message.append("\"age\":\"" + info.getAge() + "\",");
        message.append("\"country\":\"" + info.getCountry() + "\",");
        message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
        message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
        contact.setNickname(info.getNickName() + "(" + message.toString() + ")");
        contact.setContactid(info.getId());
        ContactSqlManager.insertContact(contact);

        SDKCoreHelper.init(this, ECInitParams.LoginMode.FORCE_LOGIN);
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        showToastShort(msg);
        dismissPostingDialog();
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        showToastShort(msg);
        dismissPostingDialog();
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
//        if(eventTag == ApiConstants.EventTags.ACCOUNT_LOGIN){
//            //账号登录
//            if(status){
//                mPostingdialog = new ECProgressDialog(this, R.string.login_posting);
//                mPostingdialog.show();
//            }else{
//                mPostingdialog.dismiss();
//            }
//        }
    }

    /**
     * 关闭对话框
     */
    private void dismissPostingDialog() {
        if (mPostingdialog == null || !mPostingdialog.isShowing()) {
            return;
        }
        mPostingdialog.dismiss();
        mPostingdialog = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(mPostingdialog!=null){
            mPostingdialog.dismiss();
        }
        if (requestCode == 0x2a) {
            doLauncherAction();
        }
    }

    private void doLauncherAction() {
        try {
            Intent intent = new Intent(this, LauncherActivity.class);
            intent.putExtra("launcher_from", 1);
            // 注册成功跳转
            startActivity(intent);

//            Intent service = new Intent(this, UpdateInfoService.class);
//            startService(service);

            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveAccount() throws InvalidClassException {
        String appKey = Contants.VOICE_APP_KEY;
        String token = Contants.VOICE_APP_TOKEN;
        String mobile = info.getId();
        String voippass = "";
        ClientUser user = CCPAppManager.getClientUser();
        if(user == null) {
            user = new ClientUser(mobile);
        } else {
            user.setUserId(mobile);
        }
        user.setAppToken(token);
        user.setAppKey(appKey);
        user.setPassword(voippass);
        user.setLoginAuthType(ECInitParams.LoginAuthType.NORMAL_AUTH);
        CCPAppManager.setClientUser(user);
        ECPreferences.savePreference(ECPreferenceSettings.SETTINGS_REGIST_AUTO,user.toString(), true);
        // ContactSqlManager.insertContacts(contacts);
        ArrayList<ECContacts> objects = ContactLogic.initContacts();
        objects = ContactLogic.converContacts(objects);
        ContactSqlManager.insertContacts(objects);
    }

    @Override
    protected void handleReceiver(Context context, Intent intent) {
        // super.handleReceiver(context, intent);
        int error = intent.getIntExtra("error", -1);
        if (SDKCoreHelper.ACTION_SDK_CONNECT.equals(intent.getAction())) {
            // 初始注册结果，成功或者失败
            if (SDKCoreHelper.getConnectState() == ECDevice.ECConnectState.CONNECT_SUCCESS
                    && error == SdkErrorCode.REQUEST_SUCCESS) {

                dismissPostingDialog();
                try {
                    saveAccount();
                } catch (InvalidClassException e) {
                    e.printStackTrace();
                }
                ContactsCache.getInstance().load();
                doLauncherAction();
                return;
            }
            if (intent.hasExtra("error")) {
                if (SdkErrorCode.CONNECTTING == error) {
                    return;
                }
                if (error == -1) {
                    ToastUtil.showMessage("Login failed");
                }else {
                    dismissPostingDialog();
                }
                ToastUtil.showMessage("Login failed");
            }
            dismissPostingDialog();
        }


    }
}
